<template>
  <basic-card title="报价规则" class="page-container">
    <template #body>
      <s-table
        ref="fTable"
        :height="500"
        :data.sync="tableData"
        :columns="columns"
        :show-operation="true"
        :editable="isEditor"
        operation-width="100px"
      >
        <template #pieceRange="{row, $index}">
          <div class="table-cell startRate-cell">
            <z-input-number
              v-model="row.pieceVolumeStart"
              :min="0"
              :max="100"
              size="small"
              :controls="false"
              placeholder="开始值"
              :disabled="true"
            ></z-input-number>
            <span class="cell-divider">＜ 件量 ≤ </span>
            <z-input
              v-model="row.inputValue"
              class="end-input"
              size="small"
              :placeholder="'请输入结束值'"
              @clear="clearInput($index)"
              @blur="handleEndBlur($index)"
            ></z-input>
          </div>
        </template>
        <template #default="{ $index}">
          <z-button v-if="$index !== 0" type="text-danger" @click="handleDelete($index)">删除</z-button>
        </template>
      </s-table>
    </template>
  </basic-card>
</template>
<script>
import basicCard from '@/views/pages/baseManagement/view/components/basicCard.vue'
// 获取基础信息
import { mapGetters, mapActions } from 'vuex'
import { tableConfigKey } from '@/config/common'
import { isNaN } from '@zto/z-utils-es'
import { getTableColumns, MAX_PIECE } from './config'

export default {
  name: 'basicInfo',
  components: {
    basicCard
  },
  props: {
    quoteInfo: {
      type: Object,
      default: () => null
    }
  },
  data() {
    const { quoteId, tempId, batchNo, modifyType, subCostType } = this.$route.query
    return {
      tempId,
      quoteId,
      isEditor: true,
      pageKey: `${tableConfigKey}-rulesTable`,
      tableData: [
        {
          pieceVolumeStart: 0,
          pieceVolumeEnd: Infinity,
          inputValue: '∞'
        }
      ]
    }
  },
  computed: {
    ...mapGetters('quote', ['getQuoteInfo']),
    quoteBasicInfo() {
      const quoteInfo = this.getQuoteInfo(this.tempId || this.quoteId)
      return quoteInfo ? quoteInfo.quoteBasicInfo : null
    },
    columns() {
      return getTableColumns()
    }
  },
  methods: {
    async validate() {
      const valid = await this.$refs.fTable.validate()
      // 确定给后端传正无穷还是一个固定的值
      return valid
    },
    // 获取规则数据
    getRulesData() {
      return this.tableData
    },
    /**
     * 获取段的原终点显示值
     */
    getOriginalEndDisplay(index) {
      const nextSegment = this.tableData[index + 1]
      return nextSegment ? nextSegment.pieceVolumeStart : '∞'
    },
    /**
     * 恢复段的原终点
     */
    restoreSegment(index) {
      const originalEnd = this.getOriginalEndDisplay(index)
      this.$set(this.tableData[index], 'inputValue', originalEnd)
    },

    /**
     * 解析输入值，处理 `∞`
     */
    parseValue(value) {
      if (!value || isNaN(Number(value))) {
        return Infinity
      }
      return Number(value)
    },
    /**
     * 确保最后一段的终点为 `∞`
     */
    ensureLastSegment() {
      const last = this.tableData[this.tableData.length - 1]
      if (last.pieceVolumeEnd !== Infinity) {
        this.$set(last, 'pieceVolumeEnd', Infinity)
        this.$set(last, 'inputValue', '∞')
      }
    },
    /**
     * 检查段终点是否合法
     */
    isValidSegment(pieceVolumeEnd, pieceVolumeStart, currentIndex) {
      const nextSegment = this.tableData[currentIndex + 1]
      return pieceVolumeEnd > pieceVolumeStart && (!nextSegment || pieceVolumeEnd < nextSegment.pieceVolumeEnd)
    },
    /**
     * 输入框失去焦点时验证输入并恢复或更新
     * @param index
     */
    handleEndBlur(index) {
      const current = this.tableData[index]
      const newValue = this.parseValue(current.inputValue)
      // 判断输入值必须为正整数
      if (newValue < 0 || !Number.isInteger(newValue)) {
        this.$message.warning('输入值必须为正整数')
        this.restoreSegment(index)
        return
      }
      // 限制最多可配置20条数据
      if (this.tableData.length >= 20) {
        this.$message.warning('件量区间最多可配置20段')
        return
      }
      if (MAX_PIECE < newValue) {
        this.restoreSegment(index)
        return
      }
      // 检查输入值是否合法
      if (!this.isValidSegment(newValue, current.pieceVolumeStart, index)) {
        this.restoreSegment(index)
        return
      }
      // 更新段终点
      this.$set(current, 'pieceVolumeEnd', newValue)
      this.$set(current, 'inputValue', newValue === Infinity ? '∞' : newValue)
      // 更新下一段的起点
      this.updateNextSegmentStart(index, newValue)
      // 确保最后一段的终点为 `∞`
      this.ensureLastSegment()
    },
    /**
     * 更新下一段的起点
     */
    updateNextSegmentStart(index, newEnd) {
      const nextSegment = this.tableData[index + 1]
      if (nextSegment) {
        this.$set(nextSegment, 'pieceVolumeStart', newEnd)
        // 最后一段不输入的情况
      } else if (newEnd !== Infinity) {
        // 添加新段
        this.tableData.push({
          pieceVolumeStart: newEnd,
          pieceVolumeEnd: Infinity,
          inputValue: '∞'
        })
        ++this.key
      }
    },
    /**
     * 清空输入框中的值
     */
    clearInput(index) {
      if (this.tableData[index].inputValue === '∞') {
        this.$set(this.tableData[index], 'inputValue', '')
      }
    },
    handleDelete(index) {
      const current = this.tableData[index]
      // 如果不是最后一段
      if (index !== this.tableData.length - 1) {
        // 上一段的结束值
        this.$set(this.tableData[index - 1], 'pieceVolumeEnd', current.pieceVolumeStart)
        this.$set(this.tableData[index - 1], 'inputValue', current.pieceVolumeStart)
        // 下一段的开始值
        this.$set(this.tableData[index + 1], 'pieceVolumeStart', current.pieceVolumeStart)
      }
      this.tableData.splice(index, 1)

      this.ensureLastSegment() // 确保最后一段的结束值为无穷大
    }
  }
}
</script>
<style lang="scss" scoped>
.page-container {
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 8px;
  padding: 16px;
}

.table-cell {
  align-items: center;
  display: flex;
  justify-content: center;
  width: calc(100% - 16px);
  .z-icon-edit {
    margin-left: 6px;
  }
  &.startRate-cell {
    width: calc(100% - 30px);
  }
  .cell-divider {
    flex-shrink: 0;
    padding: 0 6px;
  }

  .z-input-number input {
    width: 85px;
  }
  .end-input {
    width: 130px;
    .z-input--small .z-input__inner {
      text-align: center;
    }
  }
}
</style>
